from flask import Blueprint, request
from service.user_service import UserService
from response.result import JsonResult, StatusCode  # 导入自定义的 JsonResult

user_bp = Blueprint('user_bp', __name__)

@user_bp.route('/users', methods=['GET'])
def get_users():
    users = UserService.get_users()
    return JsonResult.ok(users).to_response()  # 返回成功结果

@user_bp.route('/user/<int:user_id>', methods=['GET'])
def get_user(user_id):
    user = UserService.get_user(user_id)
    if user:
        return JsonResult.ok(user).to_response()  # 返回找到的用户
    return JsonResult.error(StatusCode.NOT_FOUND).to_response()  # 用户未找到，返回404

@user_bp.route('/user', methods=['POST'])
def create_user():
    data = request.get_json()
    if not data or 'username' not in data or 'email' not in data:
        return JsonResult.error(StatusCode.INVALID_DATA).to_response()  # 数据不合法，返回400

    user = UserService.add_user(data['username'], data['email'])
    return JsonResult.ok(user).to_response()  # 返回新创建的用户信息，状态码201

@user_bp.route('/user/<int:user_id>', methods=['DELETE'])
def delete_user(user_id):
    if UserService.remove_user(user_id):
        return JsonResult.ok({"message": "User deleted successfully"}).to_response()  # 删除成功
    return JsonResult.error(StatusCode.NOT_FOUND).to_response()  # 删除失败，返回404
